<?php
//引入系统配置文件
include_once('config/init.php');
include_once('check.php');

//判断是否有post过来数据
$action = isset($_POST['action']) ? trim($_POST['action']) : '';

//如果等于delete 就说明是ajax发送过来 要删除数据
if($action == "delete")
{
    //封装一个返回结果
    $success = [
        'result' => false,
        'msg' => ''
    ];
    //获取到删除的id数据
    $ids = isset($_POST['ids']) ? trim($_POST['ids']) : 0;

    // var_dump($ids);
    // exit;

    //先查询出要删除的数据
    $sql = "SELECT * FROM {$pre_}person WHERE id IN($ids)";
    $dellist = all($sql);

    if(empty($dellist))
    {
        $success['result'] = false;
        $success['msg'] = '暂无删除的数据';

        //将php的数据转换为json的类型，然后并返回给前端的ajax
        echo json_encode($success);
        exit;
    }

    //先从二维数组中，抽离出指定的字段，放到一个一位数组
    $avatar = array_column($dellist, "avatar");

    //将数组中的空元素去除 去空
    $avatar = array_filter($avatar);

    //先删除数据，在删除图片
    $where = "id IN($ids)";
    $affect = delete('person', $where);
    
    if($affect)
    {
        //删除成功
        //先判断图片的数组不是空再去删除
        if(!empty($avatar))
        {
            //循环删除，必须要图片真实存在，再去删除， 不存在
            foreach($avatar as $file)
            {
                //is_file 判断文件是否存在，如果存在返回true
                is_file("./".$file) && @unlink("./".$file);
            }
        }

        $success['result'] = true;
        $success['msg'] = '删除成功';
    }else
    {
        //删除失败
        $success['result'] = false;
        $success['msg'] = '删除失败';
    }

    //返回结果
    echo json_encode($success);
    exit;
}

//当前页码
$page = isset($_GET['page']) ? trim($_GET['page']) : 1;

//每页显示多少条
$limit = 5;

//中间显示多少个页码数
$size = 5;

//sql查询数据总数
$sql = "SELECT COUNT(id) AS c FROM {$pre_}person";
$count = find($sql);
$count = isset($count['c']) ? trim($count['c']) : 0;

//调用分页函数
$html = page($page, $count, $limit, $size, 'black2');

//偏移量
$start = ($page-1)*$limit;

//链表查询
// 员工表.depid = 部门表.id
// 员工表.jobid = 职位表.id
$sql = "SELECT person.*,dep.name AS depname,job.name AS jobname FROM {$pre_}person AS person LEFT JOIN {$pre_}department AS dep ON person.depid = dep.id LEFT JOIN {$pre_}job AS job ON person.jobid = job.id ORDER BY person.id DESC LIMIT $start,$limit";

//调用函数
$list = all($sql);

// var_dump($list);
// exit;

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- 引入公共样式 -->
        <?php include_once('meta.php');?>

        <!-- 分页样式 -->
        <link rel="stylesheet" href="assets/css/page.css" />

        <style>
            .avatar{
                width:100px;
                height:100px;
                display: block;
                overflow: hidden;
            }

            .avatar img{
                width:100%;
            }
        </style>
    </head>

    <body>
        <!-- 引入头部 -->
        <?php include_once('header.php');?>

        <!-- 引入菜单 -->
        <?php include_once('menu.php');?>

        <div class="content">
            <div class="header">
                <h1 class="page-title">员工列表</h1>
            </div>
            <ul class="breadcrumb">
                <li><a href="index.php">Home</a> <span class="divider">/</span></li>
                <li class="active">员工列表</li>
            </ul>

            <div class="container-fluid">
                <div class="row-fluid">
                    <div class="btn-toolbar">
                        <button class="btn btn-primary" onClick="location='PersonAdd.php'"><i class="icon-plus"></i>添加员工</button>
                    </div>
                    <div class="well">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="toggle" /></th>
                                    <th>ID</th>
                                    <th>姓名</th>
                                    <th>性别</th>
                                    <th>手机号</th>
                                    <th>邮箱</th>
                                    <th>头像</th>
                                    <th>部门</th>
                                    <th>职位</th>
                                    <th>入职时间</th>
                                    <th style="width: 60px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($list as $item){?>
                                <tr>
                                    <td><input type="checkbox" name="list" value="<?php echo $item['id'];?>" /></td>
                                    <td><?php echo $item['id'];?></td>
                                    <td><?php echo $item['name'];?></td>
                                    <?php if($item['sex'] == '0'){?>
                                        <td>保密</td>
                                    <?php }else if($item['sex'] == '1'){?>
                                        <td>男</td>
                                    <?php }else if($item['sex'] == '2'){?>
                                        <td>女</td>
                                    <?php }else{?>
                                        <td></td>
                                    <?php }?>
                                    <td><?php echo $item['mobile'];?></td>
                                    <td><?php echo $item['email'];?></td>
                                    <?php if(is_file("./".$item['avatar'])){?>
                                        <td>
                                            <a class="avatar" href="<?php echo "./".$item['avatar'];?>" target="_blank">
                                                <img src="<?php echo "./".$item['avatar'];?>">
                                            </a>
                                        </td>
                                    <?php }else{ ?>
                                        <td>暂无头像</td>
                                    <?php }?>
                                    <td><?php echo $item['depname'];?></td>
                                    <td><?php echo $item['jobname'];?></td>
                                    <td><?php echo date("Y-m-d", $item['createtime']);?></td>
                                    <td>
                                        <a href="PersonEdit.php?id=<?php echo $item['id'];?>"><i class="icon-pencil"></i></a>
                                        <a class="delone" data-ids="<?php echo $item['id'];?>" href="#myModal" role="button" data-toggle="modal">
                                            <i class="icon-remove"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php }?>
                                <tr>
                                    <td colspan="20">
                                        <!-- 点击是一个锚点 href = id属性 -->
                                        <a class="btn btn-success delall" href="#myModal" role="button" data-toggle="modal">
                                            <i class="icon-remove"></i> 批量删除
                                        </a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <?php echo $html;?>
                    
                    <!-- 模态框的元素 -->
                    <div class="modal small hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                            <h3 id="myModalLabel">删除提示框</h3>
                        </div>
                        <div class="modal-body">
                            <p class="error-text"><i class="icon-warning-sign modal-icon"></i>是否确认删除?</p>
                        </div>
                        <div class="modal-footer">
                            <button class="btn" data-dismiss="modal" aria-hidden="true">取消</button>
                            <button class="btn btn-danger confirm" data-dismiss="modal">确认删除</button>
                        </div>
                    </div>

                    <footer>
                        <hr>
                        <p>&copy; 2017 <a href="#" target="_blank">copyright</a></p>
                    </footer> 
                </div>
            </div>
        </div>
    </body>
</html>
<script>
    //全局变量
    var ids = []

    //多条删除 复选框全选反选
    $("#toggle").click(function(){
        //获取到元素选中或取消的值
        // $(this).prop('checked')

        //列表循环的  复选框 
        $("input[name=list]").prop("checked", $(this).prop('checked'))
    })

    //点击了  批量删除
    $(".delall").click(function(){
        //获取到所有选中的复选框的值
        var list = $("input[name=list]:checked")
        
        if(list.length <= 0)
        {
            alert('未选择删除的元素')
            return false;
        }

        var arr = []

        //循环元素
        list.each(function(index, item){
            //往数组里面追加元素
            arr.push(item.value)
        })

        //覆盖全局变量
        ids = arr

        // console.log(ids)
    })

    //单条删除
    $('.delone').click(function(){
        //拿到点击元素身上ids属性 删除id

        //data方法 获取元素身上的 data- 开头的自定义属性
        var id = $(this).data('ids')
        
        //将拿到的值塞到全局数组中
        ids = [id]

        // console.log(ids)
    })

    //点击了确认删除按钮
    $(".confirm").click(function(){

        //手动关闭模态框
        $("#myModal").modal('hide')

        //将数组转换为字符串
        var str = ids.join(',')
        
        //发送ajax请求
        $.ajax({
            type:'post',  //请求类型
            dataType: 'json', //返回的数据类型
            data: {action: 'delete', ids: str},
            success:function(success)
            {
                if(success.result)
                {
                    location.href = "PersonList.php";
                }else
                {
                    alert(success.msg)
                }
                
                return false;
            },
            error: function(error)
            {
                console.log(error)
            }
        })
    })
</script>